<template>
  <div class="hello">
    <div
      ref="mapNode"
      id="normal-map"
      style="height: 600px;width: 100%;margin: 10px auto;background: #091527;"
    ></div>
  </div>
</template>

<script>
  import { geoJson } from './geoJson' // 引入
  import L from './leaflet.china'
  import 'leaflet/dist/leaflet.css'
  // import imageIcon from './../assets/logo.png'

  const normalm = L.tileLayer.chinaProvider('TianDiTu.Normal.Map', {
    maxZoom: 18,
    minZoom: 2,
  })
  // const normalm = L.tileLayer.chinaProvider('GaoDe.Normal.Map', {
  //   maxZoom: 18,
  //   minZoom: 2,
  // })
  const normala = L.tileLayer.chinaProvider('TianDiTu.Normal.Annotion', {
    maxZoom: 18,
    minZoom: 2,
  })
  const imgm = L.tileLayer.chinaProvider('TianDiTu.Satellite.Map', {
    maxZoom: 18,
    minZoom: 2,
  })
  const imga = L.tileLayer.chinaProvider('TianDiTu.Satellite.Annotion', {
    maxZoom: 18,
    minZoom: 2,
  })
  const normal = L.layerGroup([normalm, normala])
  // const normal = L.layerGroup([normalm])
  const image = L.layerGroup([imgm, imga])

  const baseLayers = {
    地图: normal,
    影像: image,
  }

  const overlayLayers = {}
  export default {
    name: 'HelloWorld',
    props: {
      msg: String,
    },
    data() {
      return {
        scale: 1,
        map: null,
        geoJSON_layer: null,
        info: null,
      }
    },
    mounted() {
      this.$nextTick(() => {
        this.initMap(this.$refs.mapNode)
      })
    },
    methods: {
      initMap(node) {
        let map = this.map
        map = L.map(node, {
          center: [36.004989, 113.205285],
          zoom: 4,
          // layers: [normal],
          zoomControl: false,
        })
        L.control
          .zoom({
            zoomInTitle: '放大',
            zoomOutTitle: '缩小',
          })
          .addTo(map)
        //右上角的那个框框叫info，这是定义他的语句
        // const info = L.control()
        //注意，想和鼠标滑进、滑出、点击有交互的时候，得在相应的函数里update
        L.control.layers(baseLayers, overlayLayers).addTo(map)
        this.geojson_layer = L.geoJSON(geoJson, {
          // 中国Geo数据
          //设置一个onEachFeature函数，接受mouseover/mouseout/click函数传来的操作
          onEachFeature: (feature, layer) => {
            //绑定弹窗
            layer.bindPopup(() => {
              return this.handlePopupContent(feature)
            }, {className: 'popup-wrapper', closeButton: false})
            // 设置省会城市名称
            const myDiv = L.divIcon({
              // iconSize: [25, 25],
              // iconAnchor: [22, 94],
              // popupAnchor: [-3, -76],
              // shadowSize: [68, 95],
              // shadowAnchor: [22, 94],
              className: 'circle-icon',
              html: `<div style="color: white;
                         display: flex;
                         position: absolute;
                         flex-direction: column;
                         justify-content: center;
                         transform: translateX(-50%);">
                         <span style="
                         position: absolute;
                         z-index: -1;
                         top: -4px;
                         left: 0;
                         right: 0;
                         margin: auto;
                         border-radius: 100%;
                         border: 1px solid #23DEFF;
                         background: #0B224E;
                         height: 50px;
                         width: 50px"></span>
                 <span style="min-width: 120px;font-size: 13px;text-align: center;">${feature.properties.name}</span>
                 <span style="min-width: 100px;text-align: center;">2890</span>
                 </div>`,
            })
            // const myIcon = L.icon({
            //   iconUrl: imageIcon,
            //   iconSize: [12, 14],
            //   // iconAnchor: [22, 94],
            //   // popupAnchor: [-3, -76],
            //   // shadowSize: [68, 95],
            //   // shadowAnchor: [22, 94],
            // })
            if (( feature.properties.centroid &&
              feature.properties.centroid.length > 0 ) || ( feature.properties.center &&
              feature.properties.center.length > 0 )) {
              const _latlng = feature.properties.centroid &&
              feature.properties.centroid.length > 0
                ? L.latLng(
                  layer.feature.properties.centroid[1],
                  layer.feature.properties.centroid[0])
                : L.latLng(
                  layer.feature.properties.center[1],
                  layer.feature.properties.center[0])
              let _layers = []
              _layers.push(L.marker(_latlng, {icon: myDiv}))
              // _layers.push(L.marker(_latlng, {icon: myIcon}))
              const myGroup = L.layerGroup(_layers)
              map.addLayer(myGroup)
            }
            // 接受mouseover/mouseout/click函数传来的操作
            this.layerInit(layer)
          },
          //定义一个设置style的函数，style中的fillColor属性由getColor函数传入
          style: (feature) => {
            return {
              fillColor: feature.properties.color
                ? feature.properties.color
                : '#222d51', // 覆盖颜色
              fillOpacity: 1, // 覆盖颜色透明度
              color: '#080E26', //图形外面划线的颜色
              weight: 2, // 图形外面划线宽度
              opacity: 1,
              dashArray: '0', //图形外面划的线为虚线
            }
          },
        }).addTo(map)
      },
      // 多边形需要执行的操作
      layerInit(Layer) {
        //mouseover事件
        Layer.on({
          //设置一个鼠标如果放置在上面，他会做什么的函数。传入onEachFeature中的mouseover
          //这里的函数作用是：鼠标在上面时设置一个加粗的边框，style如下所示
          mouseover: (e) => {
            e.target.openPopup()
            // 给当前hover上的layer设置样式
            this.geojson_layer._setLayerStyle(e.target, {
              fillColor: '#636a84', // 覆盖颜色
              fillOpacity: 1, // 覆盖颜色透明度
              color: '#080E26', //图形外面划线的颜色
              weight: 2, // 图形外面划线宽度
              opacity: 1,
              dashArray: '0', //图形外面划的线为虚线
            })
            //如果不是 ie/opera/edge 浏览器，就将修改过的，带粗灰色边框的图层，提到最前面来
            if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
              this.geojson_layer.bringToFront()
            }
          },
          //设置一个鼠标从上面移开时应该做什么的函数，传入onEachFeature中的mouseout
          //这个函数的作用：鼠标如果移开了，将所有的style回复原样
          mouseout: (e) => {
            // 移除时重置样式
            this.geojson_layer.resetStyle(e.target)
            // e.target.closePopup()
          },
          click: (e) => {
            console.log('fitBounds----click', e.target)
            e.target.openPopup()
          },
        })
      },
      // 弹窗回调函数
      handlePopupContent(feature) {
        // let _popupContent = '<p style="background: gold;"> ' + feature.properties.name + '</p>'
        // if (feature.properties && feature.properties.popupContent) {
        //   _popupContent += feature.properties.popupContent
        // }
        console.log('candy--打印:feature', feature)
        const self = this
        return this.setProvinceTooltip(null, self)
      },
      formatterNumber(number) {
        function split(number) {
          var num = number.toString()
          var i = num.indexOf(',') > 0 ? num.indexOf(',') : num.indexOf('.')
          i = i < 0 ? num.length - 3 : i - 3
          num = num.substring(0, i) + ',' + num.substring(i)
          if (i < 1) {
            return number
          } else {
            return split(num)
          }
        }

        var regex = /^(-?\d+)(\.\d+)?$/
        if (!regex.test(number)) {
          return number
        }
        var num = number.toString()
        var symbol = num.substr(0, 1)
        if (symbol === '-') {
          num = num.substr(1)
          return symbol + split(num)
        } else {
          return split(number)
        }
      },
      /**
       * author：candy
       * 绘制地图省级信息提示框
       * @param {Object} option 相关配置数据
       * @param {Object} self this指向
       * series[0].tooltip
       */
      setProvinceTooltip(option, self) {
        if (!option) {
          option = {
            name: '测试项目弹窗',
            data: {
              inbuildProjectCount: 23,
              totalAmount: 400000,
              displayBuildingVolumeDtoList: [{
                buildingVolumeUnit: 380,
                buildingVolume: 400
              }],
              thisYearProjectTotal: 3678
            }
          }
        }
        let _li = ''
        let textFontSize = 18
        let numFontSize = 24
        let _total = 0
        let resultTotalAmount = 0
        const formatAmount = function (unit) {
          if (unit <= 5) {
            _total = unit
          } else {
            let res = unit / 2
            if (res > 5) {
              formatAmount(res)
            } else {
              _total = res
            }
          }
        }
        if (option.data && option.data.inbuildProjectCount && option.data.totalAmount) {
          /**
           * 原来的合同总金额
           * resultTotalAmount = option.data.totalAmount
           */
          /**
           * 处理过的合同总金额，保留一位数
           * */
          formatAmount(option.data.totalAmount / option.data.inbuildProjectCount)
          resultTotalAmount = ( _total * option.data.inbuildProjectCount ).toFixed(1)
        }


        if (option.data && option.data.displayBuildingVolumeDtoList) {
          for (let i = 0; i < option.data.displayBuildingVolumeDtoList.length; i++) {
            let item = option.data.displayBuildingVolumeDtoList[i]
            _li += `<li class="flex-1 flex-column">
              <span class="nowrap" style="font-size:${textFontSize *
            self.scale}px;margin-bottom: ${( textFontSize - 12 ) *
            self.scale}px;">建筑体量（${item.buildingVolumeUnit}）</span>
              <span class="fc_00DEFF" style="font-size: ${numFontSize * self.scale}px">${
              item.buildingVolume }</span></li>`
          }
        } else {
          _li += ` <li
              class="flex-1 flex-column">
              <span class="nowrap" style="font-size:${textFontSize *
          self.scale}px;margin-bottom: ${( textFontSize - 12 ) *
          self.scale}px;">建筑体量</span>
              <span class="fc_00DEFF" style="font-size: ${numFontSize *
          self.scale}px">0.0</span>
            </li>`
        }
        let _html = `<div class="modal-item" style="position: relative;transition: all 300ms ease-in-out;">
                      <div class="module borderCorner-modal-wrapper" style="border-radius: ${20 *
        self.scale}px">
                          <div class="topLeft" style="width: ${20 *
        self.scale}px;height:${20 * self.scale}px"></div>
                          <div class="topRight" style="width: ${20 *
        self.scale}px;height:${20 * self.scale}px"></div>
                          <div class="bottomLeft" style="width: ${20 *
        self.scale}px;height:${20 * self.scale}px"></div>
                          <div class="bottomRight" style="width: ${20 *
        self.scale}px;height:${20 * self.scale}px"></div>
                      </div>
                      <div style="padding: ${20 * self.scale}px ${20 * self.scale}px;">
                        <div style="font-size:${( numFontSize + 6 ) * self.scale}px">${option.name}</div>
                        <ul class="flex-row flex-wrap justify-between" style="padding-top:${10 *
        self.scale}px;width:100%;padding-left: 0;">
                          <li class="flex-1 flex-column">
                            <span class="nowrap" style="font-size:${textFontSize *
        self.scale}px;margin-bottom: ${( textFontSize - 12 ) * self.scale}px;">在建项目（个）</span>
                            <span style="font-size: ${numFontSize *
        self.scale}px" class="fc_00DEFF">${option.data && option.data.inbuildProjectCount
          ? self.formatterNumber(option.data.inbuildProjectCount)
          : '0'}</span>
                          </li>
                          <li class="flex-1 flex-column">
                            <span class="nowrap" style="font-size:${textFontSize *
        self.scale}px;margin-bottom: ${( textFontSize - 12 ) * self.scale}px;">本年新开项目（个）</span>
                            <span style="font-size: ${numFontSize *
        self.scale}px" class="fc_00DEFF">${
          option.data && option.data.thisYearProjectTotal
            ? self.formatterNumber(option.data.thisYearProjectTotal)
            : '0' }</span>
                          </li>
                        </ul>
                        <ul class="flex-row flex-wrap" style="padding-top:20px;padding-left: 0;">
                          ${_li}
                          <li class="flex-1 flex-column">
                            <span class="nowrap" style="font-size:${textFontSize *
        self.scale}px;margin-bottom: ${( textFontSize - 12 ) * self.scale}px;">合同总额（亿元）</span>
                            <span style="font-size: ${numFontSize *
        self.scale}px" class="fc_00DEFF">${
          resultTotalAmount
            ? self.formatterNumber(resultTotalAmount)
            : '0.0'
          }</span>
                          </li>
                        </ul>
                      </div>
                    </div>`
        return `<div>${_html}</div>`
      }
    },
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
  .module {
    width: 100%;
    height: 100%;
  }

  .flex-1 {
    flex: 1;
  }

  .modal-item {
    animation: zoomIn 0.5s;
  }

  .nowrap {
    white-space: nowrap;
  }

  .flex-row {
    display: flex;
    flex-direction: row !important;
  }

  .flex-column {
    display: flex;
    flex-direction: column !important;
  }

  .align-center {
    align-items: center;
    -webkit-align-items: center;
    -moz-box-align: center;
    -webkit-box-align: center;
    -ms-flex-align: center;
  }

  .justify-center {
    justify-content: center;
    -webkit-justify-content: center;
    -moz-box-pack: center;
    -webkit-box-pack: center;
    -ms-flex-pack: center;
  }

  .justify-between {
    justify-content: space-between;
  }

  .fc_00DEFF {
    color: #00DEFF;
  }

  .fc_fff_opacity {
    color: rgba(255, 255, 255, 0.5);
  }

  .popup-wrapper {
    background: transparent;
    color: #fff;
  }

  .leaflet-popup-content-wrapper, .leaflet-popup-tip {
    background: transparent;
    color: #fff;
    box-shadow: unset;
  }

  .borderCorner-modal-wrapper {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: -1;
    background: rgba(24, 29, 45, 0.80);
    border: 1px solid rgba(0, 222, 255, 0.30);
    box-shadow: inset 0 0 20px 0 rgba(0, 129, 255, 0.50);
  }

  .topLeft, .topRight, .bottomLeft, .bottomRight {
    width: 100%;
    height: 100%;
    position: absolute;
  }

  .topLeft {
    top: -1px;
    left: -1px;
    background: url('./../assets/image/bordestyle1@2x.png') no-repeat;
    background-size: cover;
  }

  .topRight {
    top: -1px;
    right: -1px;
    background: url('./../assets/image/bordestyle1@2x.png') no-repeat;
    background-size: cover;
    transform: rotate(90deg);
  }

  .bottomLeft {
    bottom: -1px;
    left: -1px;
    background: url('./../assets/image/bordestyle1@2x.png') no-repeat;
    background-size: cover;
    transform: rotate(-90deg);
  }

  .bottomRight {
    bottom: -1px;
    right: -1px;
    background: url('./../assets/image/bordestyle1@2x.png') no-repeat;
    background-size: cover;
    transform: rotate(180deg);
  }

  /*单行文本溢出隐藏显示...*/
  .text-overflow {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

</style>
